package com.mall.malladminbackend.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.malladminbackend.dto.Create;
import com.mall.malladminbackend.entity.SysUser;
import com.mall.malladminbackend.mapper.SysUserMapper;
import com.mall.malladminbackend.model.PageBean;
import com.mall.malladminbackend.model.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * 作者：郭立仁
 * 描述：永无BUG
 */
@Service
public class UserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    public R selectAll(Integer pageNum,Integer pageSize,String name,String email,String mobile){
        Page<SysUser> userPage = PageHelper.startPage(pageNum, pageSize);
        sysUserMapper.selectAll(name, email, mobile);
        return R.buildSuccess(0,"success",PageBean.buildPageBean(userPage));
    }

    @Transactional
    public R delete(Integer id){
        int delete = sysUserMapper.delete(id);
        int i = sysUserMapper.deleteByUserId(id);
        return (delete+i)>0? R.buildSuccess(0,"success") : R.buildFailure(100,"删除失败");
    }

    @Transactional
    public R selectOne(Integer id){
        SysUser sysUser = sysUserMapper.selectById(id);
        return sysUser!=null? R.buildSuccess(0,"success",sysUser) : R.buildSuccess(100,"查询失败");
    }

    @Transactional
    public R updateStatus(boolean status,Integer id){
        int i = sysUserMapper.updateStatus(status, id);
        return i>0? R.buildSuccess(0,"success") : R.buildSuccess(100,"失败");
    }

    //修改用户信息和用户角色
    @Transactional
    public R update(SysUser sysUser, int[] ids, Create create){
        int update = sysUserMapper.update(sysUser, create);
        int i1 = sysUserMapper.deleteByUserId(sysUser.getId());
        int i = sysUserMapper.insertRoleByUserId(sysUser.getId(), ids, create);
        return (update+i+i1)>0 ? R.buildSuccess(0,"success") : R.buildSuccess(100,"失败");
    }

    //添加用户
    @Transactional
    public R insert(SysUser sysUser,int[] ids,Create create){
        int insert = sysUserMapper.insert(sysUser,create);
        int i = sysUserMapper.insertRoleByUserId(sysUser.getId(), ids, create);
        return (insert+i)>0 ? R.buildSuccess(0,"success") : R.buildSuccess(100,"失败");
    }
}
